import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';

import "./index.less";
import { useModel } from 'umi';
import { intl, delArray, pushNumberData, getChild, numberTotalMethod, moneyNumBerFormat } from '@/utils';

import { bottomColumns } from './SimpleDatas';
import type { guid } from 'guid-factory/lib/Guid';
import { Guid } from 'guid-factory/lib/Guid';
import notify from 'devextreme/ui/notify';
// import SavePopup from './components/SavePopup';
import { LayoutD } from '~/public/cpas-ui/components-bs/Layout';

import { DevToolBar, CpasIcon, DevGrid, LayoutB, DevPopup, DevLoading } from '~/public/cpas-ui';
import { CheckBox, SelectBox, TextArea, TextBox } from 'devextreme-react';
import { getReportItemsDatas, getZLZone, itemsDatasEditXH, ZBAdjustEditHCFSE, } from "./service"
import { getOneBillDetail, getOneBillDetailOfJZ, getReportItemsData, ZBAdjustDel, AddZBAdjust, rollBills } from '../../../service';
import { deepClone } from '~/public/cpas-business/tools/Tools';
import BigNumber from 'bignumber.js';

import { AddZBAdjustBatch } from './service';

import { SpecificPupopContext } from '../../../SpecificPupopFun';

import AgingaccountPopup from './components/AgingaccountPopup';


const AdjustEntry = React.forwardRef((props: any, ref) => {
  const { whereFrom, tableRowDel, changeEntryParamData, getCurDataBillIDRef } = props;
  const { entryParamData } = useContext<any>(SpecificPupopContext);
  const { curDataBillID, isEdit, adjustChanged, adjustChangedName, curDataYearData_ID, rollBillState } = entryParamData;

  const { setIsShowGlobalLoad } = useModel('useAdjustModel');

  const SwapArray = require('swap-array').default; // 数据上移下移的插件

  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as API.CurPart;
  const { username, usercode } = initialState?.curUser as API.CurUser;
  const { accountInfo }: any = useModel('useAdjustModel');
  const devGridRef = useRef<any>();
  const periodData = [
    {
      id: '0',
      name: '期初',
    },
    {
      id: '1',
      name: '期末',
    }
  ];

  const [dbClickDevData, setDbClickDevData] = useState<any[]>([]);
  const dbClickDevDataRef = useRef<any>([]);
  const NewRowIndexRef = useRef<any>(-1);

  const agingaccountPopupRef = useRef<any>();

  const billSelRowData = useRef<any>({});
  const [AddDataDF, setAddDataDF] = useState<string>('0.00');
  const [AddDataJF, setAddDataJF] = useState<string>('0.00');

  const AddDataDFRef = useRef<any>('0.00');
  const AddDataJFRef = useRef<any>('0.00');

  const [AccountData, setAccountData] = useState<any[]>([]);
  const [EntryData, setEntryData] = useState<any[]>([]);

  const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", marginRight: '15px' };


  const getOneBillDetails = async (dataBillId: any, isRefresh: boolean = false) => {
    const r = await getOneBillDetail(whereFrom, {
      dbname,
      billID: dataBillId,
      isRefresh,
    });
    const resTotal = numberTotalMethod(r.data);
    setAddDataDF(resTotal.totaldF_res);
    setAddDataJF(resTotal.totaljF_res);
    AddDataDFRef.current = resTotal.totaldF_res;
    AddDataJFRef.current = resTotal.totaljF_res;
    // const scrollable = devGridRef.current?.instance?.getScrollable();
    // if (scrollable) {
    //   devGridRef.current?.instance?.refresh();
    //   scrollable.scrollTo({ top: 0 });
    // }
    setDbClickDevData(r.data);
    setIsShowGlobalLoad(false);
    dbClickDevDataRef.current = r.data;
    NewRowIndexRef.current = -1;
    billSelRowData.current = {};
    return r.data;
  };
  // 获取某单据的结转分录明细
  const getOneBillDetailOfJZData = async () => {
    const rData = await getOneBillDetailOfJZ(whereFrom, {
      dbname,
      billID: curDataBillID,
    });
    setEntryData(rData.data);
  };
  const getReportBH = useCallback(async (dataId: string) => {
    const res: any = await getReportItemsDatas(whereFrom, {
      dbname,
      Data_ID: dataId,
      userCode: usercode,
    });
    if (res.success) {
      changeEntryParamData({ billNoBHNumber: res.data.billNo }, true);
      setIsShowGlobalLoad(false);
    }
  }, [usercode, whereFrom]);
  // 获取某单据的表单信息
  const getReportItemsOne = async (initObj: any) => {
    const r = await getReportItemsData(whereFrom, {
      dbname,
      billID: curDataBillID
    });
    if (r.length > 0) {

      const tempData = r[0];
      let TZLXStr = '';
      let adjustTypeStr = '';
      if (whereFrom === "审计调整") {
        if (tempData.TZLX === 2) {
          TZLXStr = '账项调整';
        } else if (tempData.TZLX === 3) {
          TZLXStr = '报表调整';
        } else if (tempData.TZLX === 4) {
          TZLXStr = '其他调整';
        };
        if (tempData.AdjustType === 1) {
          adjustTypeStr = '会计差错更正';
        } else if (tempData.AdjustType === 2) {
          adjustTypeStr = '会计政策变更';
        } else if (tempData.AdjustType === 3) {
          adjustTypeStr = '其他';
        } else {
          adjustTypeStr = '会计差错更正';
        };
      }
      let bbbbbb = {
        TZLXtypeName: whereFrom === "审计调整" ? TZLXStr : '',
        TZLXtypeID: `${tempData?.TZLX}`,
        adjustTSClassName: whereFrom === "审计调整" ? adjustTypeStr : '会计差错更正',
        adjustTSClassID: whereFrom === "审计调整" ? `${tempData?.AdjustType ?? 1}` : '1',
        // adjustShowStateSJ: tempData.TZQJ === 0,
        jzsbqqcVal: tempData.IsRetrospect,
        isTZVal: tempData.isTZ,
        curDataBillID: curDataBillID,
        adjustChanged: tempData.TZQJ === 0 ? "0" : "1",
        adjustChangedName: tempData.TZQJ === 0 ? "期初" : "期末",
        remarksMemo: tempData.remarks,
        billNoBHNumber: tempData.billNo,
      };
      // setCustomizeName(tempData.TZQJ === 0 ? "期初" : "期末");
      changeEntryParamData({ ...initObj, ...bbbbbb }, true);
    }

  };

  const fetchData = async (newYear: string) => {

    // console.log(whereFrom, newYear, "@@@ fetchData");

    let findTemp = -2;
    // const auditAdjustId: any = window.localStorage.getItem('selectDefaultTool');
    // const tempYear = JSON.parse(auditAdjustId)?.accountAdjustId ?? sjnd;
    const tempYear = newYear || sjnd;
    // console.log(newYear, accountInfo, sjnd, tempYear, '@@@');
    if (accountInfo?.length) {
      const res: any = accountInfo;
      findTemp = res.findIndex((item: any) => {
        return tempYear === item.Data_ID
      });

      const resWithIndex = res.map((item: any, index: any) => {
        item.index = index;
        return item;
      });
      setAccountData(resWithIndex);
      const tempIndex = findTemp >= 0 ? findTemp : 0;
      const DataId = res[tempIndex]?.Data_ID;
      let initObj = {
        TZLXtypeName: whereFrom === "审计调整" && !isEdit ? '账项调整' : '',
        adjustTSClassName: whereFrom === "审计调整" ? '会计差错更正' : '',
        // adjustShowStateSJ: adjustChanged === "0",
        jzsbqqcVal: isEdit ? false : true,
        isTZVal: isEdit ? false : true,
        TZLXtypeID: whereFrom === "审计调整" ? "2" : '0',
        adjustTSClassID: '1',
        curDataBillID: curDataBillID,
        newYearSelectText: res[tempIndex]?.displayName,
        remarksMemo: '',
        curDataYearData_ID: `${DataId}`,
        toolBarNotSave: isEdit
      };
      // debugger;
      // setCustomizeName(adjustChanged === "0" ? "期初" : "期末");
      if (DataId) {
        setEntryData([]);
        if (isEdit) {
          await getReportItemsOne(initObj);
          //  获取数据
          await getOneBillDetails(curDataBillID);
          // 获取下方数据
          getOneBillDetailOfJZData();
        } else {
          if (whereFrom !== "审计调整") {
            devGridRef.current?.instance.columnOption("isHCFSE", "visible", adjustChanged === "0");
          }

          changeEntryParamData(initObj, true);

          getReportBH(DataId);
        }

      }
    }
  };

  useEffect(() => {
    if (whereFrom && curDataYearData_ID && !rollBillState) {
      fetchData(curDataYearData_ID);
    }
  }, [whereFrom, curDataYearData_ID, rollBillState]);
  // ---------------------------------------------------------------------------------------------------

  // 刷新单据
  const DocumentRefresh = useCallback(() => {
    if (!entryParamData.isEdit) return;
    getReportItemsOne(entryParamData);
    getOneBillDetails(entryParamData.curDataBillID);
    getOneBillDetailOfJZData();
    // settoolBarNotSave(diaParams.current?.args?.isEdit);
  }, [entryParamData]);


  // 调整期间
  const onSelectionAdjustChanged = useCallback(async (e: any) => {
    if (e.selectedItem.id === '0' && whereFrom === '账表调整') {
      const tempDevData = [...dbClickDevData];

      for (let index = 0; index < tempDevData.length; index++) {
        const item = tempDevData[index];
        if (item.isHCFSE) {
          const res = await ZBAdjustEditHCFSE({
            dbname,
            billID: entryParamData.curDataBillID,
            GUID: item.GUID,
            isHCFSE: "false",
            isEditHCFSE: true
          });
          if (res.success) {
            item.isHCFSE = false;
          } else {
            notify('修改失败！', 'error', 2000);
          }
        }
      }
      setDbClickDevData(tempDevData);
      dbClickDevDataRef.current = tempDevData;
    }
    let newData = {};
    if (whereFrom === '审计调整') {
      newData = {
        // adjustShowStateSJ: e.selectedItem.id === '0',
        adjustChanged: e.selectedItem.id,
        adjustChangedName: e.selectedItem.name
      }
    } else {
      newData = {
        adjustChanged: e.selectedItem.id,
        adjustChangedName: e.selectedItem.name
      }
    }
    changeEntryParamData(newData);
    // setCustomizeName(e.selectedItem.name);

  }, [whereFrom, entryParamData, dbClickDevData]);

  // 左侧 工具条 账套等方法
  const onSelectionChangeds = useCallback((e: any) => {
    // console.log(e.selectedItem, '@@@ e.selectedItem.Data_ID');
    changeEntryParamData({
      newYearSelectText: e.selectedItem.displayName,
      curDataYearData_ID: `${e.selectedItem.Data_ID}`,
    }, true);
    getReportBH(e.selectedItem.Data_ID);
  }, []);


  // 特殊调整分类
  const onSelectClassificationChanged = useCallback((e: any) => {
    changeEntryParamData({
      adjustTSClassName: e.selectedItem.name,
      adjustTSClassID: e.selectedItem.id
    });

  }, []);


  // 调整类型
  const onSelectionAdjustType = useCallback((e: any) => {
    changeEntryParamData({
      TZLXtypeName: e.selectedItem.name,
      TZLXtypeID: e.selectedItem.id
    });
  }, []);

  const savedRowDataFunCom = useCallback((AddData: any) => {
    changeEntryParamData({ toolBarNotSave: false });
    const resTotal = numberTotalMethod(dbClickDevData);
    setAddDataDF(resTotal.totaldF_res);
    setAddDataJF(resTotal.totaljF_res);
    AddDataDFRef.current = resTotal.totaldF_res;
    AddDataJFRef.current = resTotal.totaljF_res;

    const resJF = pushNumberData(AddData?.JF);
    const resDF = pushNumberData(AddData?.DF);
    const resultJF = Number(resJF.truncatedNumber);
    const resultDF = Number(resDF.truncatedNumber);
    if (AddData?.GUID) {
      let saveData: any = {
        dbname,
        billID: entryParamData.curDataBillID,
        GUID: AddData.GUID,
        Data_ID: entryParamData.curDataYearData_ID,
        KMBH: AddData.KMBH,
        KMMC: AddData.KMMC,
        YSKMBH: `${AddData.YSKMBH}`,
        YSKMMC: AddData.YSKMMC,
        itemNames3: AddData.itemNames3,
        YSHSXMBH: AddData.YSHSXMBH,
        YSHSXMMC: AddData.YSHSXMMC,
        HSXMBH: AddData.HSXMBH,
        HSXMMC: AddData.HSXMMC,
        HSXMLXBH: AddData.HSXMLXBH,
        HSXMLXMC: AddData.HSXMLXMC,
        JF: resultJF,
        DF: resultDF,
        remark: AddData.remark ? AddData.remark : '',
        PKMBH: AddData.PID === '0' ? '' : AddData.PKMBH,
        XH: AddData.XH
      };
      // let tempXH;
      if (whereFrom === "审计调整") {
        saveData = { ...saveData, isHCFSE: "0" };
      } else {
        saveData = {
          ...saveData,
          isHCFSE: `${AddData.isHCFSE}`
        };
      }
      AddZBAdjust(whereFrom, saveData);
    };
  }, [dbClickDevData, entryParamData, whereFrom]);


  // 保存行事件
  const savedRowDataFunc = (data: any) => {
    if (data.changes?.length) {
      savedRowDataFunCom(data.changes[0].data);
    }
  }
  // 分录明细表格单击事件 TopCellClick
  const TopCellClick = (cell: any) => {
    if (cell?.data && cell?.rowIndex !== -1) {
      if (!cell?.data?.YSKMBH || !cell?.data?.YSKMMC || !cell?.data?.itemNames3) {
        billSelRowData.current = cell.data;
      } else {
        billSelRowData.current = {};
      }
    }
    dbClickDevDataRef.current = dbClickDevData;
  };

  // const onCellDblClick = async (cell: any) => {
  //   if (!cell?.data) return;
  //   if (cell?.data?.JF || cell?.data?.DF) return;
  //   let JFNumber = 0;
  //   let DFNumber = 0;
  //   let qStr = '0.00';
  //   // const resTotal = numberTotalMethod(dbClickDevData);
  //   // JFNumber = Number(resTotal.totaljF_resNumber);
  //   // DFNumber = Number(resTotal.totaldF_resNumber);

  //   const resTotalJF = pushNumberData(AddDataJF);
  //   const resTotalDF = pushNumberData(AddDataDF);
  //   JFNumber = Number(resTotalJF.truncatedNumber);
  //   DFNumber = Number(resTotalDF.truncatedNumber);
  //   // const resTotal = numberTotalMethod(dbClickDevData);
  //   // setAddDataDF(resTotal.totaldF_res);
  //   // setAddDataJF(resTotal.totaljF_res);
  //   console.log(AddDataJF, AddDataDF, '@@@ savedRowDataFunCom,DF, onCellDblClick'); 
  //   debugger;
  //   if (cell && cell?.column?.dataField === "JF") {
  //     qStr = `${DFNumber - JFNumber}`;
  //   }
  //   if (cell && cell?.column?.dataField === "DF") {
  //     qStr = `${JFNumber - DFNumber}`;
  //   }
  //   let q1 = 0;
  //   const resQ = pushNumberData(qStr);
  //   if (resQ) {
  //     q1 = Number(resQ.truncatedNumber);
  //   }
  //   let tempRow = { ...cell.data };
  //   if (cell && cell?.column?.dataField === "JF") {
  //     if (JFNumber || JFNumber === 0) {
  //       q1 = q1;
  //     } else if (JFNumber !== DFNumber) {
  //       q1 = JFNumber * -1;
  //     }
  //     console.log({ ...tempRow, JF: q1 }, '@@@ savedRowDataFunCom,JF, onCellDblClick');
  //     tempRow = { ...tempRow, JF: q1 };
  //     // return savedRowDataFunCom(tempRow, true);
  //     // await devGridRef.current.instance.cellValue(cell.row.rowIndex, 'JF', q1);
  //   };

  //   if (cell && cell?.column?.dataField === "DF") {
  //     if (DFNumber || DFNumber === 0) {
  //       q1 = q1;
  //     } else if (JFNumber !== DFNumber) {
  //       q1 = DFNumber * -1;
  //     }
  //     console.log({ ...tempRow, DF: q1 }, '@@@ savedRowDataFunCom,DF, onCellDblClick');
  //     tempRow = { ...tempRow, DF: q1 };
  //     // return savedRowDataFunCom(tempRow, true);
  //     // await devGridRef.current.instance.cellValue(cell.row.rowIndex, 'DF', q1);
  //   }
  //   await devGridRef.current.instance.saveEditData();
  //   // debugger;
  //   // await devGridRef.current.instance.cancelEditData();
  // }


  const onCellDblClick = useCallback((cell: any) => {
    if (!cell?.data) return;
    if (cell?.data?.JF || cell?.data?.DF) return;
    let JFNumber = 0;
    let DFNumber = 0;
    let qStr = '0.00';
    // const resTotal = numberTotalMethod(dbClickDevData);
    // JFNumber = Number(resTotal.totaljF_resNumber);
    // DFNumber = Number(resTotal.totaldF_resNumber);

    const resTotalJF = pushNumberData(AddDataJFRef.current);
    const resTotalDF = pushNumberData(AddDataDFRef.current);
    JFNumber = Number(resTotalJF.truncatedNumber);
    DFNumber = Number(resTotalDF.truncatedNumber);
    // debugger;
    if (cell && cell?.column?.dataField === "JF") {
      qStr = `${DFNumber - JFNumber}`;
    }
    if (cell && cell?.column?.dataField === "DF") {
      qStr = `${JFNumber - DFNumber}`;
    }
    let q1 = 0;
    const resQ = pushNumberData(qStr);
    if (resQ) {
      q1 = Number(resQ.truncatedNumber);
    }
    let tempRow = { ...cell.data };
    if (cell && cell?.column?.dataField === "JF") {
      if (JFNumber || JFNumber === 0) {
        q1 = q1;
      } else if (JFNumber !== DFNumber) {
        q1 = JFNumber * -1;
      }
      console.log({ ...tempRow, JF: q1 }, '@@@ savedRowDataFunCom,JF, onCellDblClick');
      tempRow = { ...tempRow, JF: q1 };
      devGridRef.current.instance.cellValue(cell.row.rowIndex, 'JF', q1);
    };

    if (cell && cell?.column?.dataField === "DF") {
      if (DFNumber || DFNumber === 0) {
        q1 = q1;
      } else if (JFNumber !== DFNumber) {
        q1 = DFNumber * -1;
      }
      console.log({ ...tempRow, DF: q1 }, '@@@ savedRowDataFunCom,DF, onCellDblClick');
      tempRow = { ...tempRow, DF: q1 };
      // return savedRowDataFunCom(tempRow, true);
      devGridRef.current.instance.cellValue(cell.row.rowIndex, 'DF', q1);
    }
    devGridRef.current.instance.saveEditData();
    devGridRef.current.instance.cancelEditData();
  }, [AddDataDFRef.current, AddDataJFRef.current]);

  const addRowFunc = useCallback((pushNewData: any, addGUID: string) => {
    let asdasda = 0;
    setDbClickDevData((arr: any) => {

      const ars = [...arr];
      const arsXH = ars.length + 1;
      asdasda = arsXH;
      ars.push({ ...pushNewData, GUID: addGUID, XH: arsXH });

      const resTotal = numberTotalMethod(ars);
      setAddDataDF(resTotal.totaldF_res);
      setAddDataJF(resTotal.totaljF_res);
      AddDataDFRef.current = resTotal.totaldF_res;
      AddDataJFRef.current = resTotal.totaljF_res;
      return ars;
    });
    return asdasda;
  }, [dbClickDevData]);

  const addRowFuncReplacement = useCallback((pushNewObj: any) => {
    setDbClickDevData((arr: any) => {
      let ars1 = [...arr];  // 复制数组以保持不可变性
      for (let index = 0; index < ars1.length; index++) {
        if (ars1[index].GUID === pushNewObj.GUID) {
          ars1[index] = { ...ars1[index], ...pushNewObj };  // 直接修改数组中的元素
          console.log(ars1[index], '@@@ updated element');
        }
      };
      const resTotal1 = numberTotalMethod(ars1);
      setAddDataDF(resTotal1.totaldF_res);
      setAddDataJF(resTotal1.totaljF_res);
      AddDataDFRef.current = resTotal1.totaldF_res;
      AddDataJFRef.current = resTotal1.totaljF_res;
      return ars1;  // 返回新的数组
    });
  }, [dbClickDevData]);


  // 获取 点击树结构 数据
  const treeDblClickGetGridData_fun = useCallback(async (data: any) => {
    const pushNewData = deepClone(data);
    if (pushNewData?.ID) {
      console.log(billSelRowData.current, '@@@ billSelRowData.current');
      // addRowFunc(pushNewData);
      const addGUID: guid = Guid.newGuid();
      let saveData: any = {};
      if (billSelRowData.current?.GUID) {
        saveData = {
          ...billSelRowData.current,
          KMBH: pushNewData.KMBH,
          KMMC: pushNewData.KMMC,
          YSKMBH: `${pushNewData.YSKMBH}`,
          YSKMMC: pushNewData.YSKMMC,
          itemNames3: pushNewData.itemNames3,
          YSHSXMBH: pushNewData.YSHSXMBH,
          YSHSXMMC: pushNewData.YSHSXMMC,
          HSXMBH: pushNewData.HSXMBH,
          HSXMMC: pushNewData.HSXMMC,
          HSXMLXBH: pushNewData.HSXMLXBH,
          HSXMLXMC: pushNewData.HSXMLXMC,
          PKMBH: pushNewData.PID === '0' ? '' : pushNewData.PKMBH,
        };
        const pushNewObj = deepClone(saveData);
        addRowFuncReplacement(pushNewObj);
      } else {
        const arsXH = addRowFunc(pushNewData, addGUID);
        saveData = {
          billID: entryParamData.curDataBillID,
          GUID: addGUID,
          Data_ID: entryParamData.curDataYearData_ID,
          KMBH: pushNewData.KMBH,
          KMMC: pushNewData.KMMC,
          YSKMBH: `${pushNewData.YSKMBH}`,
          YSKMMC: pushNewData.YSKMMC,
          itemNames3: pushNewData.itemNames3,
          YSHSXMBH: pushNewData.YSHSXMBH,
          YSHSXMMC: pushNewData.YSHSXMMC,
          HSXMBH: pushNewData.HSXMBH,
          HSXMMC: pushNewData.HSXMMC,
          HSXMLXBH: pushNewData.HSXMLXBH,
          HSXMLXMC: pushNewData.HSXMLXMC,
          JF: pushNewData?.JF ?? null,
          DF: pushNewData?.DF ?? null,
          remark: pushNewData?.remark ?? "",
          PKMBH: pushNewData.PID === '0' ? '' : pushNewData.PKMBH,
          XH: arsXH
        };
      }
      // let tempXH;
      if (whereFrom === "审计调整") {
        saveData = { ...saveData, isHCFSE: "0" };
      } else {
        saveData = {
          ...saveData,
          isHCFSE: `${pushNewData.isHCFSE}`
        };
      }
      await AddZBAdjust(whereFrom, { dbname, ...saveData });
      billSelRowData.current = {};
    }
  }, [addRowFunc, addRowFuncReplacement, billSelRowData.current, entryParamData]);



  // 获取 批量 点击树结构 数据
  const treeBatchGetGridData_fun = useCallback(async (dataArr: any) => {
    // let dataArrLen = dataArr.length - 1;
    // let aaaa = false;
    let aaaaa = dbClickDevData.length + 1;
    let paramsData: any[] = [];
    for (let index = 0; index < dataArr.length; index++) {
      const element = dataArr[index];
      const pushNewData = deepClone(element);
      if (pushNewData?.ID) {
        const addGUID: guid = Guid.newGuid();
        const arsXH = aaaaa + index;
        let saveData: any = {
          // dbname,
          billID: entryParamData.curDataBillID,
          GUID: addGUID,
          Data_ID: entryParamData.curDataYearData_ID,
          KMBH: pushNewData.KMBH,
          KMMC: pushNewData.KMMC,
          YSKMBH: `${pushNewData.YSKMBH}`,
          YSKMMC: pushNewData.YSKMMC,
          itemNames3: pushNewData.itemNames3,
          YSHSXMBH: pushNewData.YSHSXMBH,
          YSHSXMMC: pushNewData.YSHSXMMC,
          HSXMBH: pushNewData.HSXMBH,
          HSXMMC: pushNewData.HSXMMC,
          HSXMLXBH: pushNewData.HSXMLXBH,
          HSXMLXMC: pushNewData.HSXMLXMC,
          JF: pushNewData?.JF ?? null,
          DF: pushNewData?.DF ?? null,
          remark: pushNewData?.remark ?? "",
          PKMBH: pushNewData.PID === '0' ? '' : pushNewData.PKMBH,
          XH: arsXH,
          rowState: 'insert'
        };
        if (whereFrom === "审计调整") {
          saveData = { ...saveData, isHCFSE: "0" };
        } else {
          saveData = {
            ...saveData,
            isHCFSE: `${pushNewData.isHCFSE}`
          };
        }
        paramsData.push(saveData);
      }
    }

    const res = await AddZBAdjustBatch(dbname, entryParamData.curDataBillID, paramsData);


    if (res.success) {
      await getOneBillDetails(entryParamData.curDataBillID, true);
      return true;
    }
    return false;



  }, [addRowFunc, dbClickDevData, entryParamData]);



  // 自定义方法
  useImperativeHandle(ref, () => ({
    DocumentRefreshRef: () => {
      DocumentRefresh();
    },
    getOneBillDetailOfJZDataRef: async () => {
      await getOneBillDetailOfJZData();
    },
    getOneBillDetailsRef: async (dataBillId: any, isRefresh: boolean = false) => {
      await getOneBillDetails(dataBillId, isRefresh);
    },
    treeDblClickGetGridData: async (nodeData: any) => {
      await treeDblClickGetGridData_fun(nodeData);
    },

    treeBatchGetGridData: async (nodeData: any[]) => {
      const res = await treeBatchGetGridData_fun(nodeData);
      return res;
    },
    openAdjustTableRef: () => {
      if (devGridRef.current) {
        return devGridRef.current
      }
    },
    getdbClickDevData: () => {
      return {
        NewRowIndexRef: NewRowIndexRef.current,
        dbClickDevData,
        AdjustTableData: dbClickDevDataRef.current,
        AddDataDF,
        AddDataJF
      }
    },
    setdbClickDevDataRef: (newData: any) => {
      dbClickDevDataRef.current = newData;
      setDbClickDevData(newData);
      const resTotal = numberTotalMethod(newData);
      setAddDataDF(resTotal.totaldF_res);
      setAddDataJF(resTotal.totaljF_res);
    },
  }));




  const GetFiltration = (rowData_arr: any) => {
    const transformedData = rowData_arr.map((item: any) => {
      const transformedItem = {};
      const monthKeys = ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'];
      const yearKeys = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8', 'Y9', 'Y10'];
      Object.keys(item).forEach((key) => {
        if (monthKeys.includes(key) || yearKeys.includes(key)) {
          transformedItem[key] = item[key];
        }
      });
      return transformedItem;
    });
    return transformedData;
  };
  const changeGetFiltration = async (rowData: any) => {
    setIsShowGlobalLoad(true);
    const formData = GetFiltration([rowData]);
    const arr = rowData.KMMC.split('-');
    const resolvess = arr[0];
    console.log(rowData, ' @@@  rowData');

    if (rowData?.DF && rowData?.JF) {
      notify('借方金额 和 贷方金额不能同时输写!', 'error', 2000);
      setIsShowGlobalLoad(false);
    } else {
      const res = await getZLZone({
        dbname,
        KMMC: resolvess
      });
      if (res.success) {
        let tempObj = {};
        const DFValueJF = rowData?.JF;
        const DFValueDF = rowData?.DF;
        if (rowData?.DF || !rowData?.DF && !rowData?.JF) {
          const formatDF = pushNumberData(`${DFValueDF}`);
          tempObj = { name: '贷方金额', JE: formatDF.formattedPrice };
        }
        if (rowData?.JF) {
          const formatJF = pushNumberData(`${DFValueJF}`);
          tempObj = { name: '借方金额', JE: formatJF.formattedPrice };
        }
        setIsShowGlobalLoad(false);
        agingaccountPopupRef.current.show({
          args: {
            title: '调整金额分配账龄区间',
            KMBH: rowData.YSKMBH,
            KMMC: rowData.KMMC,
            data: res.data,
            GUID: rowData.GUID,
            FZZMC: rowData.HSXMMC,
            transformedData: formData,
            ...tempObj
          },
          okCallback: () => {
            getOneBillDetails(rowData.billID, true);
            changeEntryParamData({ toolBarNotSave: false });
          },
        });
      } else {
        setIsShowGlobalLoad(false);
      }
    }
  }



  // 左侧 top 单据分录明细表格 账表调整
  const columnsZB = [
    {
      dataField: "XH",
      dataType: "string",
      caption: "序号",
      width: 80,
      alignment: "center",
      allowEditing: false,
      allowUpdating: false,
      // cellRender: (cell: any) => {
      //   return cell.rowIndex + 1
      // }
    },
    {
      dataField: "itemNames3",
      dataType: "string",
      caption: "报表项目",
      width: 100,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "YSKMBH",
      dataType: "string",
      caption: "科目编号",
      width: 100,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "KMMC",
      dataType: "string",
      caption: "科目名称",
      minWidth: 180,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "HSXMMC",
      dataType: "string",
      caption: "辅助账名称",
      width: 180,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "isHCFSE",
      dataType: "boolean",
      caption: "是否红冲本期发生",
      width: 100,
      alignment: "center",
    },
    {
      dataField: "JF",
      caption: "借方金额",
      dataTypeCustom: "money-number",
      dataType: "number",
      editorOptions: {
        format: '#,##0.##',
      },
      width: 120,
      alignment: "right",
      allowEditing: true,
    },
    {
      dataField: "DF",
      caption: "贷方金额",
      dataTypeCustom: "money-number",
      dataType: "number",
      editorOptions: {
        format: '#,##0.##',
      },
      width: 120,
      alignment: "right",
      allowEditing: true,
    },
    {
      dataField: "ZLArea",
      dataType: "string",
      caption: "账龄区间",
      width: 80,
      alignment: "right",
      allowEditing: false,
      allowUpdating: false,
      cellRender: (cell: any) => {
        // cellRef.current = cell.data;
        let tempZLArea = '';
        if (cell.data.ZLArea) {
          tempZLArea = cell.data.ZLArea;
        }
        return <>
          <span>{tempZLArea}</span>
          <CpasIcon type='icon-ellipsis' onClick={() => {
            changeGetFiltration(cell.data);
          }} />
        </>
      }
    },
    {
      dataField: "remark",
      dataType: "string",
      caption: "备注",
      width: 100,
      alignment: "left",
    }
  ];

  // 左侧 top 单据分录明细表格 审计调整
  const columnsSJ = [
    {
      dataField: "XH",
      dataType: "string",
      caption: "序号",
      width: 80,
      alignment: "center",
      allowEditing: false,
      allowUpdating: false,
      // cellRender: (cell: any) => {
      //   return cell.rowIndex + 1
      // }
    },
    {
      dataField: "itemNames3",
      width: 100,
      dataType: "string",
      caption: "报表项目",
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "YSKMBH",
      dataType: "string",
      caption: "科目编号",
      width: 100,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "KMMC",
      dataType: "string",
      caption: "科目名称",
      minWidth: 180,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "HSXMMC",
      dataType: "string",
      caption: "辅助账名称",
      width: 180,
      alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: "JF",
      caption: "借方金额",
      dataType: "number",
      dataTypeCustom: "money-number",
      editorOptions: {
        format: '#,##0.##',
      },
      width: 120,
      alignment: "right",
      allowEditing: true,
    },
    {
      dataField: "DF",
      caption: "贷方金额",
      dataTypeCustom: "money-number",
      dataType: "number",
      editorOptions: {
        format: '#,##0.##',
      },
      width: 120,
      alignment: "right",
      allowEditing: true,
    },
    {
      dataField: "ZLArea",
      dataType: "string",
      caption: "账龄区间",
      width: 80,
      alignment: "right",
      allowEditing: false,
      allowUpdating: false,
      cellRender: (cell: any) => {
        // cellRef.current = cell.data;
        let tempZLArea = '';
        if (cell.data.ZLArea) {
          tempZLArea = cell.data.ZLArea;
        }
        return <>
          <span>{tempZLArea}</span>
          <CpasIcon type='icon-ellipsis' onClick={() => {
            changeGetFiltration(cell.data);
          }} />
        </>
      }
    },
    {
      dataField: "remark",
      dataType: "string",
      caption: "备注",
      width: 100,
      alignment: "left",
    },
  ];


  const moveListFunc = async (rowData: any, rowIndex: any, toIndex: any) => {
    if (dbClickDevDataRef.current.length === 1) return;
    const toRowGuid = dbClickDevDataRef.current[toIndex].GUID;
    const rowGuid = rowData.GUID;
    const moveRowIndex = rowIndex + 1;
    const moveToIndex = toIndex + 1;
    const billID = getCurDataBillIDRef();
    const res = await itemsDatasEditXH(whereFrom, {
      dbname,
      billID,
      rowIndex: moveRowIndex,
      rowGuid: rowGuid,
      toIndex: moveToIndex,
      toRowGuid: toRowGuid
    });
    if (res.success) {
      const moveData = SwapArray(dbClickDevDataRef.current, rowIndex, toIndex);
      const tempXh = moveData[rowIndex].XH;
      moveData[rowIndex].XH = moveData[toIndex].XH;
      moveData[toIndex].XH = tempXh;
      setDbClickDevData(moveData);
      dbClickDevDataRef.current = moveData;
      changeEntryParamData({ toolBarNotSave: false });
    } else {
      notify('移动失败', 'error', 2000);
    }

  }
  // useCallback(, [dbClickDevDataRef.current, curMoveBillID]);
  // // 分录明细 表格数据
  const topContainer = () => {
    return <div style={{ width: '100%', height: '100%' }}>
      <div style={{ width: '100%', height: 'calc(100% - 45px)', overflow: "hidden" }}>
        {useMemo(() => {
          let templeteBox: any;
          let tempColumn: any;
          if (whereFrom === "审计调整") {
            tempColumn = columnsSJ;
          } else {
            tempColumn = columnsZB;
          }

          tempColumn = [...tempColumn, {
            dataField: "",
            caption: "行操作",
            width: 100,
            alignment: "center",
            cellRender: (cell: any) => {
              return <>
                <span style={{ marginRight: '8px' }}><CpasIcon type='icon-shangchuan' fontSize={16}
                  // zIndexUp()
                  onClick={() => {
                    const tempIndex = cell.rowIndex - 1;
                    const toIndex = tempIndex === -1 ? dbClickDevDataRef.current.length - 1 : tempIndex;
                    moveListFunc(cell.data, cell.rowIndex, toIndex);
                  }} /></span>
                <span style={{ marginRight: '8px' }}><CpasIcon type='icon-xiazai' fontSize={16}
                  onClick={() => {
                    const tempIndex = cell.rowIndex + 1;
                    const toIndex = tempIndex === dbClickDevDataRef.current.length ? 0 : tempIndex;
                    moveListFunc(cell.data, cell.rowIndex, toIndex);
                  }} /></span>
                <CpasIcon type='icon-delete' fontSize={16}
                  onClick={() => {
                    tableRowDel(cell.data, cell.rowIndex);
                  }} />
              </>
            }
          }];
          console.log(whereFrom, dbClickDevData, adjustChangedName, '@@@   templeteBox');

          templeteBox = <DevGrid.RangeTap
            ref={devGridRef}
            height='100%'
            width='100%'
            // id="GUID"
            headerFilter={{ visible: false }}
            filterPanel={{ visible: false }}
            filterRow={{ visible: false }}
            paging={{
              enabled: false
            }}
            dataSource={dbClickDevData}
            keyExpr="GUID"
            defaultColumns={tempColumn}
            showBorders={true}
            showRowLines={true}
            showColumnLines={true}
            // onCellValueChanged={(e) => {
            //   if (e.column.dataField === 'DF' || e.column.dataField === 'JF') {
            //     console.log(e, '@@@ onCellValueChanged');

            //     const value = parseFloat(e.value); // 确保值是数字
            //     if (!isNaN(value)) {
            //       const roundedValue = Math.round(value * 100) / 100; // 四舍五入
            //       e.setValue(roundedValue);
            //     }
            //   }
            // }}
            // allowColumnResizing={true}
            customizeColumns={(columnsZB: any[]) => {
              // console.log(adjustChangedName, '@@@ adjustChangedName------');
              columnsZB.forEach((column: any) => {
                if (whereFrom !== "账表调整") return;
                if (column.dataField === 'isHCFSE' && adjustChangedName === "期末") {
                  column.visible = false;
                } else {
                  column.visible = true;
                }
                return column;
              });
            }}
            // loadPanel={{
            //   enabled: true,
            //   text: 'Loading...',
            // }}
            editing={{
              allowAdding: false,
              allowUpdating: true,
              allowDeleting: false,
              mode: "cell"
            }}
            scrolling={{
              mode: "virtual",
              rowRenderingMode: "virtual",
              renderAsync: true
            }}
            onSaved={savedRowDataFunc}
            onCellClick={TopCellClick}
            onCellDblClick={onCellDblClick}
            onFocusedCellChanging={(data: any) => {
              dbClickDevDataRef.current = dbClickDevData;
              NewRowIndexRef.current = data.newRowIndex;
            }}
          />
          return templeteBox
        }, [whereFrom, dbClickDevData, adjustChangedName])}
      </div>
      <div style={{ width: '100%', height: '40px', background: 'rgb(217 217 217)', display: "flex", alignItems: 'center', justifyContent: 'end' }}>
        <span style={{ marginRight: '10px', display: "flex", alignItems: 'center', }}>
          借方金额:<TextBox width={100} height='32px' value={AddDataJF} valueChangeEvent='keyup' readOnly={true} showClearButton={true} />
        </span>
        <span style={{ marginRight: '10px', display: "flex", alignItems: 'center', }}>
          贷方金额:<TextBox width={100} height='32px' value={AddDataDF} valueChangeEvent='keyup' readOnly={true} showClearButton={true} />
        </span>
      </div>
    </div>
  };

  // 左侧 bottom 结转分录 表格
  const bottomContainer = () => (<div style={{ width: '100%', height: '100%' }}>
    <div style={{ width: '100%', height: '50px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      --------------------------------- 结转分录详细 ---------------------------------
    </div>
    {useMemo(() => {
      return <DevGrid.RangeTap
        width='100%'
        height='calc(100% - 52px)'
        id="GUID"
        headerFilter={{ visible: false }}
        filterPanel={{ visible: false }}
        filterRow={{ visible: false }}
        paging={{
          enabled: false
        }}
        dataSource={EntryData}
        keyExpr="GUID"
        defaultColumns={bottomColumns}
        // focusedRowEnabled={true}
        hoverStateEnabled={true}
        showBorders={true}
        showRowLines={true}
        showColumnLines={true}
        allowColumnResizing={true}
        columnResizingMode="widget"
      />
    }, [EntryData])}

  </div>);

  return (
    <>
      <div style={{ width: '100%', height: '100%' }}>
        <div style={{ width: '100%', height: '40px', display: 'flex', overflow: "auto" }}>
          {useMemo(() => {
            return <div style={{ width: "100%", display: 'flex', alignItems: "center", justifyContent: ' space-between' }}>
              <div style={Divstyle}>
                <div style={{ width: '70px', textAlign: 'right' }}>账套：</div>
                <SelectBox
                  disabled={isEdit}
                  width={200}
                  items={AccountData}
                  displayExpr='displayName'
                  valueExpr='displayName'
                  value={entryParamData.newYearSelectText}
                  onSelectionChanged={onSelectionChangeds}
                  dropDownOptions={
                    { width: '400px' }
                  }
                />
              </div>
              <div style={Divstyle}>
                <span style={{ marginRight: '8px', whiteSpace: 'nowrap' }}> 单据编号:</span>
                <TextBox width={140} value={entryParamData.billNoBHNumber}
                  onValueChange={(value: any) => {
                    changeEntryParamData({ billNoBHNumber: value });
                  }}
                />
              </div>

              <div style={Divstyle}>
                <span style={{ marginRight: '8px', whiteSpace: 'nowrap' }}>调整期间:</span>
                <SelectBox
                  width={130}
                  items={periodData}
                  displayExpr='name'
                  valueExpr='name'
                  value={entryParamData.adjustChangedName}
                  onSelectionChanged={onSelectionAdjustChanged}
                />
              </div>
              {whereFrom === '审计调整' && <div style={{ display: "flex" }}>
                <div style={Divstyle}>
                  <span style={{ marginRight: '8px', whiteSpace: 'nowrap' }}>调整类型:</span>
                  <SelectBox
                    width={140}
                    items={[
                      {
                        id: '2',
                        name: '账项调整',
                      },
                      {
                        id: '3',
                        name: '报表调整',
                      },
                      {
                        id: '4',
                        name: '其他调整',
                      }
                    ]}
                    displayExpr='name'
                    valueExpr='name'
                    value={entryParamData.TZLXtypeName}
                    onSelectionChanged={onSelectionAdjustType}
                  />
                </div>
                {adjustChanged === "0" &&
                  <div style={Divstyle}>
                    <span style={{ marginRight: '8px', whiteSpace: 'nowrap' }}>特殊调整分类:</span>
                    <SelectBox
                      width={170}
                      items={[
                        {
                          id: '1',
                          name: '会计差错更正',
                        },
                        {
                          id: '2',
                          name: '会计政策变更',
                        },
                        {
                          id: '3',
                          name: '其他',
                        }
                      ]}
                      displayExpr='name'
                      valueExpr='name'
                      value={entryParamData.adjustTSClassName}
                      onSelectionChanged={onSelectClassificationChanged}
                    />
                  </div>}
              </div>}
              <div style={Divstyle}>
                <CheckBox value={entryParamData.isTZVal} onValueChange={(e: any) => {
                  changeEntryParamData({ isTZVal: e });
                }} />
                <span style={{ marginLeft: '8px', marginRight: '10px', whiteSpace: 'nowrap' }}>是否调整</span>
              </div>
              {adjustChanged === "0" && whereFrom === '审计调整' && <div style={Divstyle}>
                <CheckBox
                  value={entryParamData.jzsbqqcVal}
                  onValueChange={(e: any) => {
                    changeEntryParamData({ jzsbqqcVal: e });
                  }} />
                <span style={{ marginLeft: '8px', marginRight: '10px', whiteSpace: 'nowrap' }}>仅追溯本期期初</span>
              </div>}
            </div>
          }, [whereFrom, entryParamData, isEdit, dbClickDevData, AccountData])}
        </div>
        <div style={{ width: '100%', height: '45px', display: 'flex', alignItems: 'center' }}>
          <div style={{ width: '70px' }}>调整说明：</div>
          <TextArea width='92%' value={entryParamData.remarksMemo} height={35} onChange={(e: any) => {
            const { event } = e;
            changeEntryParamData({ remarksMemo: event.target.value });
          }} />
        </div>
        <div style={{ width: '100%', height: 'calc(100% - 90px)' }}>
          <LayoutD
            columnSize="100%"
            topSlot={topContainer()}
            bottomSlot={bottomContainer()}
          />


          {/* 调整金额分配账龄区间 */}
          <AgingaccountPopup ref={agingaccountPopupRef} width={750} height={600} dataBillID={curDataBillID} whereFrom={whereFrom} />
        </div>
      </div>
    </>
  );
});

export default AdjustEntry;

